<template>
  <div class="stats-panel">
    <div class="stats-panel-head stats-form">
      <h3>{{$t('report.staffCategoryChart.title1')}}
        <el-popover trigger="hover">
          <ul>
            <template v-if="state === 'personnel-workload'">
              <template v-if="categoryType === $t('common.base.task')">
                <li>{{ $t('report.staffCategoryChart.title11') }}</li>
                <li>{{ $t('report.staffCategoryChart.title12') }}</li>
              </template>
              <template v-if="categoryType === $t('common.base.customer')">
                <li>{{ $t('report.staffCategoryChart.title13') }}</li>
              </template>
            </template>
            
            <li v-if="state === 'profit-event'">{{ $t('report.staffCategoryChart.title14') }}</li>
            <li v-if="state === 'personnel-satisfaction'"> {{ $t('report.staffCategoryChart.title4') }}</li>
            <li v-if="state === 'personnel-effectiveness'">
              <div>{{$t('report.staffCategoryChart.title18')}}</div>
              <div>{{$t('report.staffCategoryChart.title15')}}</div>
              <div>{{$t('report.staffCategoryChart.title16')}}</div>
              <div>{{$t('report.staffCategoryChart.title17')}}</div>
            </li>
          </ul>
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>
      <div class="stats-form-groups">
      <div class="stats-form-group stats-checkbox">
        <base-checkbox :value="ignoreDeleted" @input="chooseCategoryDeleted">{{$t('report.staffEventTable.title2')}}</base-checkbox>
      </div>
      <div class="stats-form-group stats-checkbox">
        <base-checkbox :value="categoryIgnoreNull" @input="chooseCategoryIgnore">{{$t('report.staffCategoryChart.text2')}}</base-checkbox>
      </div>

      <biz-team-select multiple is-auto-select-child collapse class="stats-team-select biz-team-select" :value="tag" @input="chooseCategoryTeam" :fetch-func="fetchTeam" @remove="clearTeam"/>
      <!-- <div class="stats-form-group">
        <select @change="chooseCategoryTeam">
          <option value="">全部</option>
          <option v-for="team in teams" :key="team.id" :value="team.id">{{team.name}}</option>
        </select>
      </div> -->

      <div class="stats-form-group">
        <!-- <div id="date-range" class="stats-form-daterange">
          <span>{{categoryStartTime}} - {{categoryEndTime}}</span> 
          <b class="caret"></b>
        </div> -->
        <date-picker @datePicker="datePicker" type="staffEfficiency" />
      </div>
      <div class="stats-form-group stats-form-effectiveness" size='medium' v-if="state === 'personnel-effectiveness'">
        <el-radio-group v-model="timeType" @change='timeTypeChange'>
          <el-radio-button label="day">{{$t('common.base.day')}}</el-radio-button>
          <el-radio-button label="hour">{{$t('common.base.hour1')}}</el-radio-button>
          <el-radio-button label="minute">{{$t('common.base.minute')}}</el-radio-button>
        </el-radio-group>
      </div>
      </div>
      
    </div>
    <div class="stats-panel-body">
      <div style="text-align: center;">
        <div class="stats-btn-group" v-if="state === 'personnel-effectiveness'">
          <button type="button" @click="chooseCategoryType('', $t('common.tabs.event'))" v-if="!isBasicEditionHideEvent">{{$t('common.tabs.event')}}</button>
          <button type="button" :class="{'stats-checked': categoryType == $t('report.staffCategoryChart.title9')}" @click="chooseCategoryType($t('report.staffCategoryChart.title9'), $t('common.base.task'))">{{$t('common.base.task')}}</button>
          <div class="task-flex task-ai task-mr24">
            <span>{{$t('common.label.taskTemplate')}}：</span>
            <el-select v-model="taskTypes" collapse-tags multiple clearable :placeholder="$t('report.taskSelect.placeholder1')" class="task-span1" @change="Params" @clear="Params">
              <el-option
                v-for="item in taskTypesList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="stats-btn-group" v-else-if="state === 'personnel-workload'">
          <button type="button" @click="chooseCategoryType('', $t('common.tabs.event'))" v-if="!isBasicEditionHideEvent">{{$t('common.tabs.event')}}</button>
          <button type="button" :class="{'stats-checked': categoryType == $t('common.base.task')}" @click="chooseCategoryType($t('common.base.task'), $t('common.base.task'))">{{$t('common.base.task')}}</button>   
          <button type="button" :class="{'stats-checked': categoryType == $t('common.base.customer')}" @click="chooseCategoryType($t('common.base.customer'), $t('common.base.task'), t('common.base.customer'))">{{$t('common.base.customer')}}</button>
        </div>
        <div class="stats-btn-group" v-else>
          <button type="button" @click="chooseCategoryType('', $t('common.tabs.event'))" v-if="!isBasicEditionHideEvent">{{$t('common.tabs.event')}}</button>
          <button type="button" :class="{'stats-checked': categoryType == $t('common.base.degree')}" @click="chooseCategoryType($t('common.base.degree'), $t('common.base.task'))">{{ $t('common.base.task') }}</button>   
        </div>
      </div>
      <div class="category-chart-wrap">
        <div id="customer" v-show="categoryType === $t('common.base.customer')"></div>
        <div id="category" v-show="categoryType !== $t('common.base.customer')"></div>
        <stats-chart-empty v-if="categoryEmpty">{{$t('common.base.tip.noData')}}</stats-chart-empty>
      </div>
      <div class="stats-staff-category-wrap" v-if="showTable">
        <div class="stats-table-header">
          <h3>{{categoryType}}{{ $t('common.base.list') }}</h3>

          <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.export') }}</button>          
          <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
        </div>
        <div>
          <el-table :data="page.list" class="stats-table" v-if="categoryType !== $t('common.base.customer')">
            <el-table-column :label="$t('common.base.serialNumber')" prop="taskNo" width="150px" :show-overflow-tooltip="false">
              <template slot-scope="scope">
                <sample-tooltip :row="scope.row">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <el-tooltip :content="scope.row.taskNo" placement="top" :disabled="!isContentTooltip">
                      <a href="#" @click="openDetail(`taskView_${scope.row.id}`, `${$t('common.base.task')}${scope.row.taskNo}`, `/task/view/${scope.row.id}`)">{{scope.row.taskNo}}</a>
                    </el-tooltip>
                  </template>
                </sample-tooltip>
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.label.taskTemplate')" prop="templateName" width="120px"></el-table-column>
            <el-table-column :label="$t('common.base.customer')" prop="customer.name" min-width="240px"></el-table-column>
            <el-table-column label="工单收入(元)" prop="profit" width="200px" v-if="categoryType == $t('report.eventScoreChart.label3')">
              <template slot-scope="scope">
                <span>{{ scope.row.profit.toFixed(2) }}</span>
              </template>
            </el-table-column>

            <template v-if="categoryType == $t('common.base.degree')">
              <el-table-column :label="$t('common.base.degree')" prop="degree" width="100px"></el-table-column>
              <div v-if="notShowSatisfied">
                <template v-if="hasStar">
                  <el-table-column v-for="(field, index) in evaluateConfig.starEvaluates" :label="field" :prop="`evaluateObj.${evaluateConfig.starEvaluateFeilds[index]}`" :key="field"/>
                </template>
                <el-table-column :label="$t('report.eventScoreChart.label1')" width="200px" prop="evaluateObj.tagEvaluates" show-overflow-tooltip v-if="hasTag">
                  <template slot-scope="scope">{{scope.row.evaluateObj && scope.row.evaluateObj.tagEvaluates | prettyArray}}</template>
                </el-table-column>
                <el-table-column :label="$t('common.label.customerEvaluation')" width="240px" prop="evaluateContent" show-overflow-tooltip></el-table-column>
              </div>
              <el-table-column :label="$t('report.eventScoreChart.label2')" width="240px" prop="suggestion" show-overflow-tooltip></el-table-column>
            </template>    
              
            <template v-if="categoryType == $t('report.staffCategoryChart.title9')">
              <el-table-column :label="$t('task.detail.components.acceptTime')" width="180px">
                <template slot-scope="scope">
                  {{formatterTime(scope.row.acceptUsedTimeStr)}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('task.detail.components.taskTime')" width="180px">
                <template slot-scope="scope">
                  {{formatterTime(scope.row.taskUsedTimeStr)}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('task.detail.components.workTime')" width="180px">
                <template slot-scope="scope">
                  {{formatterTime(scope.row.workUsedTimeStr)}}
                </template>
              </el-table-column>
            </template>
            <el-table-column :label="$t('common.base.status')" prop="state" width="100px">
              <template slot-scope="scope">
                {{scope.row.state | taskStateName}}
              </template>
            </el-table-column>
                      
            <el-table-column :label="$t('common.label.principalName')" width="120px">
              <template v-if="scope.row.executor" slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.executor.staffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.executor.displayName }}
                </template>
              </template>
            </el-table-column>

            <el-table-column :label="$t('common.base.createUser')" width="120px">
              <template v-if="scope.row.createUser" slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.createUser.staffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.createUser.displayName }}
                </template>
              </template>
            </el-table-column>
            
            <el-table-column :label="$t('common.base.column.createTime')" width="180px">
              <template slot-scope="scope">
                {{scope.row.createTime | fmt}}
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.label.finishTime')" width="180px">
              <template slot-scope="scope">
                {{scope.row.completeTime | fmt}}
              </template>
            </el-table-column>
          </el-table>

          <!-- 客户 -->
          <el-table :data="page.list" class="stats-table" v-else>
            <el-table-column :label="item.displayName" prop="customerName" v-for="(item, index) in CUSTOMER" :key="index">
              <template slot-scope="scope">
                <template v-if="item.fieldName === 'customerNo'">
                  <a href="#" @click="openDetail(`customerView_${scope.row.id}`, $t('report.eventScoreChart.title2'), `/customer/view/${scope.row.id}?noHistory=1`)">{{scope.row[item.fieldName]}}</a>
                </template>
                <template v-else>{{scope.row[item.fieldName]}}</template>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination class="stats-pagination"
                         background @current-change="jump"
                         :current-page="page.pageNum"
                         layout="total, prev, pager, next"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { t } from '@src/locales';
import { isOpenData } from '@src/util/platform';
/* global AMap, moment, _init_data*/
import _ from 'lodash';
import http from 'src/util/HttpUtil';
import qs from 'src/util/querystring';

import echarts from 'packages/Echarts';

import Loading from 'packages/BaseLoading';
import BaseCheckbox from 'packages/BaseCheckbox.vue';
import SampleTooltip from 'packages/SampleTooltip'
import {CUSTOMER} from '../common/tableModel'

import * as ReportApi from '@src/api/ReportApi.ts';
import { isBasicEditionHideEvent } from '@shb-lib/version'
import { checkButtonDisplayed } from '@src/util/dom';
import { getThemeColor } from '@src/util/business/color'

import { useNewVue } from '@hooks/useNewVue'
const { createVue } = useNewVue();

const USER_TASK_LEGEND = [t('common.base.add'), t('common.base.finish')];
const USER_TASK_OBJ = { [t('common.base.add')]: 'taskCount', [t('common.base.finish')]: 'finishedTask' }
const USER_TASK_COLOR = ['#6da9e7', '#48e8ab'];

const USER_EXPENSE_LEGEND = [t('report.staffCategoryChart.title10')];
const USER_EXPENSE_OBJ = { [t('report.staffCategoryChart.title10')]: 'receivables' }
const USER_EXPENSE_COLOR = ['#48e8ab'];

const USER_DEGREE_LEGEND = [ t('common.base.satisfactionDegree.0'), t('common.base.satisfactionDegree.1'),t('common.base.satisfactionDegree.2'),t('common.base.satisfactionDegree.3'),t('common.base.satisfactionDegree.4')];
const USER_DEGREE_OBJ = { [t('common.base.satisfactionDegree.1')]: 'satisfication', [t('common.base.satisfactionDegree.0')]: 'verySatifaction', [t('common.base.satisfactionDegree.2')]: 'general', [t('common.base.satisfactionDegree.3')]: 'unSatisfication', [t('common.base.satisfactionDegree.4')]: 'veryUnSatifaction'}
const USER_DEGREE_COLOR = [ getThemeColor(),'#48e8ab', '#6da9e7', '#ffdd92', '#f6903d'];

const USER_EFFICIENCY_LEGEND = [t('report.common.averageTime.3'), t('report.common.averageTime.1'), t('report.common.averageTime.4')];
const USER_EFFICIENCY_COLOR = ['#48e8ab', '#6da9e7', '#ffdd92'];

let category = null;
import { safeNewDate } from '@src/util/time';
import { getRootWindow } from '@src/util/dom'
import { isEnterpriseEdition } from '@shb-lib/version'
export default {
  name: 'staff-category-chart',
  props: {
    state:{
      type: String
    },
    type: {
      type: String
    },
    evaluateConfig: {
      type: Object
    }
  },
  data(){
    return {
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      tag: [],
      sort: '',
      categoryType: '',
      tabTrackName: 'EVENT',
      categoryData: {},
      categoryIgnoreNull: Boolean(localStorage.getItem('categoryIgnoreNull') == 'true'),
      categoryStartTime: '',
      categoryEndTime: '',
      categoryTeamId: '',
      categoryEmpty: false,

      showTable: false,
      model: {
        pageNum: 1,
        userId: '',
        selectType: ''
      },
      page: {},
      myChart: '',
      customerId: '',
      customerName: '',
      CUSTOMER,
      taskTypes: [], // 工单类型
      taskTypesList: [],
      timeType: 'day',
      customerTableList: [], // 客户表格数据
      ignoreDeleted: Boolean(localStorage.getItem('ignoreDeleted') == 'true')
    }
  },
  computed: {
    hasStar(){
      return this.evaluateConfig.useStarEvaluate;
    },
    notShowSatisfied() {
      const RootWindow = getRootWindow(window);
      return !(isEnterpriseEdition()) && !(RootWindow?.grayAuth?.satisfaction)
    },
    hasTag(){
      return this.evaluateConfig.useTagEvaluate;
    },
    // 基础版功能是否隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent() 
    },
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    }
  },
  methods: {
    timeTypeChange(value) {
      localStorage.setItem('timeType', value)
      this.renderCategory();
    },
    // 参数
    Params: _.debounce(function(){
      const { taskTypes } = this
      localStorage.setItem('taskTypesList', JSON.stringify(taskTypes))
      this.renderCategory();
    }, 100),
    async getTaskTypes() {
      this.taskTypesList = []
      const {succ, data} = await ReportApi.taskType()
      if (succ) {
        for(let key in data) {
          this.taskTypesList.push({
            value: key,
            label: data[key]
          })
        }
      }
    },
    clearTeam(value = []){
      const ids = []
      value.forEach(item=>{
        ids.push(item.id)  
      })
      this.categoryTeamId = ids.join(',');
      this.renderCategory();
    },
    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    exportAllData(){
      let param = {
        timeStart: this.categoryStartTime,
        timeEnd: this.categoryEndTime,
        ignoreNull: this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted,
      }
      if (this.categoryType === t('common.base.customer')) {
        let params = {
          ...param,
          tagIds: this.categoryTeamId,
        };
        window.location.href = `/api/report/outside/stats/staff/customer/export?${ qs.stringify(params)}`;
        this.exportTrack(true)
        return
      }
      let model = {
        ...param,
        tagId: this.categoryTeam,
        timeUnit: this.timeType,
      };
      if(this.categoryType == t('report.staffCategoryChart.title9')) {
        model.taskTypeList = this.taskTypes;
      }

      let selectType = 'task';
      if(this.categoryType == t('report.eventScoreChart.label3')) selectType = 'expense';
      if(this.categoryType == t('common.base.degree')) selectType = 'degree';
      if(this.categoryType == t('report.staffCategoryChart.title9')) selectType = 'time';

      model.selectType = selectType;
      window.location.href = `/api/report/outside/stats/executorTask/exportAll?${ qs.stringify(model)}`;

      this.exportTrack(true)
    },
    exportData(){
      let param = {
        timeStart: this.categoryStartTime,
        timeEnd: this.categoryEndTime,
        ignoreNull: this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted,
      }
      if (this.categoryType === t('common.base.customer')) {
        let params = {
          ...param,
          userId: this.customerId,
          tagIds: this.categoryTeamId,
        }
        window.location.href = `/api/report/outside/stats/staff/customer/export?${ qs.stringify(params)}`;
        this.exportTrack(false)
        return
      }
      let model = {
        ...param,
        tagId: this.categoryTeamId,
        userId: this.model.userId,
        selectType: this.model.selectType,
        timeUnit: this.timeType,
      };
      if(this.categoryType == t('report.staffCategoryChart.title9')) {
        model.taskTypeList = this.taskTypes;
      }

      window.location.href = `/api/report/outside/stats/executorTask/export?${ qs.stringify(model)}`;

      this.exportTrack(false)
    },
    exportTrack(isExportAll) {
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.state,
        tab: this.tabTrackName
      }, '*')
    },
    openDetail(id, title, url){
      let fromId = window.frameElement.getAttribute('id');

      this.$platform.openTab({
        id, 
        title, 
        close: true, 
        url,
        fromId
      });
      
    },
    fetchTableData(){
      let model = {
        tagId: this.categoryTeamId,
        timeStart: `${this.categoryStartTime }`,
        timeEnd: `${this.categoryEndTime }`,
        userId: this.model.userId,
        selectType: this.model.selectType,
        pageNum: this.model.pageNum,
        timeUnit: this.timeType,
      };
      if(this.categoryType == t('report.staffCategoryChart.title9')) {
        model.taskTypeList = this.taskTypes;
      }

      return http.post('/api/report/outside/stats/staff/taskList', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);

      try {
        this.page = await this.fetchTableData();
        this.showTable = true;
      } catch (error) {
        console.log('this.taskTypes', this.taskTypes);
        console.log(error);
      }

      instance.hide();
    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      if (this.categoryType === t('common.base.customer')) { this.customerPage({id: this.customerId, name: this.customerName}); return}
      this.renderTable();
    },
    // 时间赋值
    initDate(start, end){
      this.categoryStartTime = start;
      this.categoryEndTime = end;
      
      this.renderCategory();
    },
    // 初始化图表
    initCategory(){
      category = echarts.init(document.getElementById('category'));
      category.on('click', event => {
        let seriesName = event.seriesName;
        let origin = event.data._origin;
                
        let selectType = 'taskAdd';
        if(seriesName == t('common.base.finish')) selectType = 'taskFinish'
        if(seriesName == t('report.staffCategoryChart.title10')) selectType = 'expense'
        if(seriesName == t('common.base.satisfactionDegree.0')) selectType = 'degreeVerySatifaction'
        if(seriesName == t('common.base.satisfactionDegree.1')) selectType = 'degreeSatifaction'
        if(seriesName == t('common.base.satisfactionDegree.2')) selectType = 'degreeGeneral'
        if(seriesName == t('common.base.satisfactionDegree.3')) selectType = 'degreeUnsatifaction';
        if(seriesName == t('common.base.satisfactionDegree.4')) selectType = 'degreeVeryUnSatifaction';
        if(seriesName == t('report.common.averageTime.3')) selectType = 'acceptTime';
        if(seriesName == t('report.common.averageTime.4')) selectType = 'taskTime';
        if(seriesName == t('report.common.averageTime.1')) selectType = 'workTime';

        this.model.pageNum = 1;
        this.model.userId = origin.userId;
        this.model.selectType = selectType;

        this.renderTable()
      })
      category.on('legendselectchanged', event => {
        let arr = [];
        let opt = category.getOption();
        for(let [key, value] of Object.entries(event.selected)) {
          arr.push({key, value});
        }
        arr.some(item => {
          if(item.value) {
            this.sort = item.key;
            return true;
          }
        })

        if(this.categoryType == t('common.base.task')) {
          let sort = this.sortTaskTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        } else if (this.categoryType == t('common.base.degree')) {
          let sort = this.sortDegreeTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        } else if (this.categoryType == t('report.staffCategoryChart.title9')) {
          let sort = this.sortEfficiencyTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        }

        category.setOption(opt);
      })
      
    },
    chooseCategoryIgnore(value){
      this.categoryIgnoreNull = value;
      localStorage.setItem('categoryIgnoreNull', value)
      this.renderCategory();
    },
    chooseCategoryDeleted(value) {
      this.ignoreDeleted = value;
      localStorage.setItem('ignoreDeleted', value)
      this.renderCategory();
    },
    chooseCategoryDate(start, end){
      this.$emit('trackEvent', 'chooseDate');

      this.categoryStartTime = start;
      this.categoryEndTime = end;
      this.renderCategory();
    },
    chooseCategoryTeam(value){
      this.$emit('trackEvent', 'chooseTeam');
      localStorage.setItem('tag', JSON.stringify(value))
      // let tag = (Array.isArray(value) ? value[0] : value) || {};
      this.tag = value;
      // this.categoryTeamId = tag.id;
      
      const ids = []
      value.forEach(item=>{
        ids.push(item.id)  
      })
      this.categoryTeamId = ids.join(',');

      this.renderCategory();

      this.state && this.$track.commonFn.chartTrack(this.state, 'REPORT_SEARCH_TEAM', this.$track)
    },
    async renderCategory(event){
      try {
        if(!this.categoryStartTime || !this.categoryEndTime) return;
        let instance = Loading.show(this.$el);

        if (!this.categoryType) {
          if (this.state === 'personnel-workload' && this.type === t('common.base.task')) {
            this.categoryType = t('common.base.task')
          } else if(this.state === 'personnel-workload' && this.type === t('common.base.customer')) {
            this.categoryType = t('common.base.customer')
          } else if (this.state === 'personnel-satisfaction') {
            this.categoryType = t('common.base.degree')
          } else {
            this.categoryType = t('report.staffCategoryChart.title9')
          }
        }

        if(this.categoryType !== t('common.base.customer')) this.categoryData = await this.fetchCategoryData();

        this.setCategoryOption(event);

        if(this.categoryType === t('common.base.customer')) await this.customerCount();

        instance.hide();
        this.showTable = false;

        category && category.resize();
      } catch (error) {
        console.log(error)
      }
    },
    chooseCategoryType(type, value, showText){
      this.$emit('trackEvent', type);
      
      this.$emit('show', value)
      this.model.pageNum = 1
      if (!type) return
      this.categoryType = type;
      this.tabTrackName = ({
        [t('common.tabs.event')]: 'EVENT',
        [t('common.base.task')]: 'TASK',
        [t('common.base.customer')]: 'CUSTOMER',
      })[showText || value]
      if (type === t('common.base.customer')) {
        if (this.myChart) this.myChart.clear(); 
        if(category) category.clear()
        this.customerCount()
      } else if (type === t('common.base.task')) {
        if(category) category.clear()
        if (this.myChart) this.myChart.clear();
        this.renderCategory()
      }
      this.setCategoryOption();
    },
    setCategoryOption(event){
      this.categoryEmpty = false;
      category && category.clear();

      let option = null;
      if(this.categoryType == t('common.base.task')){
        let taskOption = this.getCategoryTaskOption();
        if(taskOption) option = this.getCategoryOption(taskOption);
      }

      if(this.categoryType == t('report.eventScoreChart.label3')){
        let expenceOption = this.getCategoryExpenceOption()
        if(expenceOption) option = this.getCategoryOption(expenceOption);
      }

      if(this.categoryType == t('common.base.degree')){
        let degreeOption = this.getCategoryDegreeOption();
        if(degreeOption) option = this.getCategoryOption(degreeOption);
      }

      if(this.categoryType == t('report.staffCategoryChart.title9')){
        let efficiencyOption = this.getCategoryEfficiencyOption()
        if(efficiencyOption) option = this.getCategoryOption(efficiencyOption);
      }
      
      if(null == option){
        this.categoryEmpty = true;
        return
      }

      category && category.setOption(option);
    },
    async handleStaffData(res, type){
      if(!res[type] || !res[type].length) return res
      let originItems = res[type].filter(item=>item.displayName || item.name)
      let items = originItems.map(item => {
        return {
          type: 'userName',
          id: item.staffId
        }
      })

      const result = await new Promise((resolve, reject) => {
        window.WWOpenData.prefetch({ items }, (err, data) => {
          if (err) {
            return reject(err)
          }
          resolve(data)
        })
      })
      
      try {
        res[type] = originItems.map((item, index) => {
          return Object.assign(item, { displayName: result.items[index].data })
        })
      } catch (error) {
        console.warn(error)
      }

      return res
    },
    fetchCategoryData(){
      let params = {
        timeStart: this.categoryStartTime,
        timeEnd: this.categoryEndTime,
        tagId: this.categoryTeamId,
        ignoreNull: this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted
      };
      if(this.categoryType == t('report.staffCategoryChart.title9')) {
        this.taskTypes =  JSON.parse((localStorage.getItem('taskTypesList')))
        params.timeUnit = this.timeType;
        params.taskTypeList = this.taskTypes || [];
      }
      return http.post('/api/report/outside/stats/staff/userCount', params).then(async res=>{
        if (this.isOpenData) {
          if (window.WWOpenData?.initCanvas) {
            window.WWOpenData.initCanvas()
            window.WWOpenData.enableCanvasSharing()
          }
          
          let allHandleStaffDataPromise = Object.keys(res).map(item =>{
            return this.handleStaffData(res, item)
          })
          
          await Promise.all(allHandleStaffDataPromise)
        }
        return res
      })
    },
    // 客户
    async customerCount() {
      if(!this.categoryStartTime || !this.categoryEndTime) return;
      
      let params = {
        timeStart: this.categoryStartTime,
        timeEnd: this.categoryEndTime,
        tagIds: this.categoryTeamId ? this.categoryTeamId.split(',') : [],
        ignoreNull: this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted
      };
      let data = await ReportApi.customerCount(params)
      if (this.isOpenData && data && data.length) {
        if (window.WWOpenData?.initCanvas) {
          window.WWOpenData.initCanvas()
          window.WWOpenData.enableCanvasSharing()
        }
        let originItems = data
        let items = originItems.map(item => {
          return {
            type: 'userName',
            id: item.staffId
          }
        })
        
        const result = await new Promise((resolve, reject) => {
          window.WWOpenData.prefetch({ items }, (err, data) => {
            if (err) {
              return reject(err)
            }
            resolve(data)
          })
        })
        
        try {
          data = originItems.map((item, index) => {
            return Object.assign(item, { name: result.items[index].data })
          })
        } catch (error) {
          console.warn(error)
        }
      }

      if (data.length && this.categoryType === t('common.base.customer')) this.categoryEmpty = false
      if (!data.length) {
        this.customerTableList = [];
        if (this.myChart) this.myChart.clear();
        return;
      }  

      this.customerTableList = data; 
      if(!this.myChart) this.initCustoreChart();

      this.customerChare(data)
    },
    // 初始化客户柱状图
    initCustoreChart(data){
      this.myChart = echarts.init(document.getElementById('customer'));
      this.myChart.on('click', (e) => {
        this.model.pageNum = 1;
        let item = this.customerTableList.filter(item => {return item.name === e.name})[0]
        this.customerPage(item)
      })
    },
    // 客户柱状图
    customerChare(data) {
      let that = this
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          max: 'dataMax',
        },
        yAxis: {
          type: 'category',
          data: data.map(item => {return item.name}),
          axisLabel: {
            formatter(originText) {
              if (!originText) return '';
              if(originText.length <= 7 || that.isOpenData) {
                return originText
              }
              return `${originText.slice(0, 7)}...`;
            }
          },
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        dataZoom: [
          {
            show: true,
            yAxisIndex: 0,
            filterMode: 'empty',
            width: 30,
            height: '80%',
            showDataShadow: false,
            left: '93%'
          }
        ],
        series: [{
          realtimeSort: true,
          name: t('report.staffTaskTable.title5'),
          type: 'bar',
          barWidth : 30,
          itemStyle: {
            normal: {
              color: '#55b7b4'
            }
          },
          data: data.map(item => {return item.count}),
          label: {
            show: true,
            position: 'right',
          }
        }],
        legend: {
          show: true,
          left: 60
        }
      };

      this.myChart.setOption(option);
    },
    // 人员工作量统计分页
    async customerPage(item) {
      let instance = this.$loading.show(this.$el);

      try{
      this.customerId = item.id
      this.customerName = item.name
      let params = {
        userId: item.id,
        timeStart: this.categoryStartTime,
        timeEnd: this.categoryEndTime,
        tagIds: this.categoryTeamId ? this.categoryTeamId.split(',') : [],
        ignoreNull: this.categoryIgnoreNull,
        pageNum: this.model.pageNum
      };
      const res = await ReportApi.customerPage(params)
      let list = {list:res.list.map(v => {
        v['customerName'] = v.name
        return v
      })}
      this.page = {...res, ...list}
      this.showTable = true

      instance.hide();
      }catch(e){
        instance.hide();
      }
    },
    getCategoryEfficiencyOption(){
      let ctx = this;
      let data = this.categoryData.efficiency || [];

      if(data.length == 0) return null;
      let yAxisData = [];
      let series = [];
      let aauTime = []; // 平均接单用时
      let atuTime = []; // 平均工单用时
      let awuTime = []; // 平均工作用时

      let maxData = 0;
      // data.sort((prev, next) => prev.AverageAcceptUsedTime - next.AverageAcceptUsedTime);
      data.forEach(item => {
        yAxisData.push(item.displayName);

        aauTime.push({
          value: item.AverageAcceptUsedTime, 
          _origin: item
        });

        atuTime.push({
          value: item.AverageTaskUsedTime,
          _origin: item
        });

        awuTime.push({
          value: item.AverageWorkUsedTime,
          _origin: item
        });

        if(item.AverageAcceptUsedTime >= maxData) maxData = item.AverageAcceptUsedTime;
        if(item.AverageTaskUsedTime >= maxData) maxData = item.AverageTaskUsedTime;
        if(item.AverageWorkUsedTime >= maxData) maxData = item.AverageWorkUsedTime;
      });

      series.push({
        name: USER_EFFICIENCY_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: aauTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: awuTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        data: atuTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      let interval = this.computeInterval(maxData);

      let option = {
        title: t('report.statistics.title6'),
        legend: USER_EFFICIENCY_LEGEND,
        color: USER_EFFICIENCY_COLOR,
        tooltip: {
          formatter(data){
            let html = '';
            if(ctx.isOpenData) {
              let staffId = data[0].data._origin.staffId
              let id = Math.ceil(Math.random() * 1000)
              html = `<ww-open-data type="userName" openid="${staffId}" id="wwOpenData${id}"></ww-open-data>`
              setTimeout(() => {
                window.WWOpenData && window.WWOpenData.bind(document.getElementById(`wwOpenData${id}`))
              }, 500);
            }else {
              let name = data[0].name;
              html += `<div>${name}</div>`;
            }

            data.forEach(item => {
              html += `<div>${item.marker} ${item.seriesName}: ${ctx.formatterTime(item.value)}</div>`;
            })

            return html;
          }
        },
        xAxis: {
          axisLabel: {
            show: true,
            formatter (value, index) {
              let temp = ctx.formatterTime(value);
              return temp == '--' ? 0 : temp;
            }
          }
        },
        yAxisData,
        series
      }

      // if(interval.min != null) option.xAxis.minInterval = interval.min;
      // if(interval.max != null) option.xAxis.maxInterval = interval.max;

      return option;
    },
    sortEfficiencyTable () {
      let data = this.categoryData.efficiency || [];

      if(data.length == 0) return null;
      let yAxisData = [];
      let series = [];
      let aauTime = []; // 平均接单用时
      let atuTime = []; // 平均工单用时
      let awuTime = []; // 平均工作用时

      let maxData = 0;

      if(this.sort == t('report.common.averageTime.3')) {
        data.sort((prev, next) => prev.AverageAcceptUsedTime - next.AverageAcceptUsedTime);
      } else if(this.sort == t('report.common.averageTime.4')) {
        data.sort((prev, next) => prev.AverageTaskUsedTime - next.AverageTaskUsedTime);
      } else {
        data.sort((prev, next) => prev.AverageWorkUsedTime - next.AverageWorkUsedTime);
      }
      data.forEach(item => {
        yAxisData.push(item.displayName);

        aauTime.push({
          value: item.AverageAcceptUsedTime, 
          _origin: item
        });

        atuTime.push({
          value: item.AverageTaskUsedTime,
          _origin: item
        });

        awuTime.push({
          value: item.AverageWorkUsedTime,
          _origin: item
        });

        if(item.AverageAcceptUsedTime >= maxData) maxData = item.AverageAcceptUsedTime;
        if(item.AverageTaskUsedTime >= maxData) maxData = item.AverageTaskUsedTime;
        if(item.AverageWorkUsedTime >= maxData) maxData = item.AverageWorkUsedTime;
      });

      series.push({
        name: USER_EFFICIENCY_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: aauTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: awuTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        data: atuTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        series,
        yAxisData
      }
    },
    getCategoryTaskOption(){
      let data = this.categoryData.taskCount || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let createdData = [];
      let finishedDate = [];
      let series = [];
      
      data.sort((prev, next) => prev.taskCount - next.taskCount).forEach(item => {
        yAxisData.push(item.displayName);
        createdData.push({
          value: item.taskCount,
          _origin: item
        });
        finishedDate.push({
          value: item.finishedTask,
          _origin: item
        });
      });
      
      series.push({
        name: USER_TASK_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: createdData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_TASK_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: finishedDate,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        title: t('report.statistics.title11'),
        legend: USER_TASK_LEGEND,
        color: USER_TASK_COLOR,
        yAxisData,
        series
      }
    },
    sortTaskTable () {
      let data = this.categoryData.taskCount || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let createdData = [];
      let finishedDate = [];
      let series = [];
      
      if(this.sort == t('common.base.finish')) {
        data.sort((prev, next) => prev.finishedTask - next.finishedTask);
      } else {
        data.sort((prev, next) => prev.taskCount - next.taskCount);
      }
      data.forEach(item => {
        yAxisData.push(item.displayName);
        createdData.push({
          value: item.taskCount,
          _origin: item
        });
        finishedDate.push({
          value: item.finishedTask,
          _origin: item
        });
      });

      series.push({
        name: USER_TASK_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: createdData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_TASK_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: finishedDate,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        series,
        yAxisData
      }
    },
    getCategoryExpenceOption(){
      let data = this.categoryData.expense || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let expenseData = [];
      let series = [];

      data.sort((prev, next) => prev.receipt - next.receipt).forEach(item => {
        yAxisData.push({
          value: item.displayName,
          _origin: item
        });
        expenseData.push({
          value: item.receipt,
          _origin: item
        });
      });

      series.push({
        name: USER_EXPENSE_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: expenseData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        title: t('report.statistics.title10'),
        legend: USER_EXPENSE_LEGEND,
        color: USER_EXPENSE_COLOR,
        yAxisData,
        series
      }
    },
    getCategoryDegreeOption(){
      let series = [];
      let data = this.categoryData.degree || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let verySatisData = [] // 非常满意
      let satisData = [];// 满意
      let generaldData = [];// 一般
      let unsatisData = []; // 不满意
      let veryUnSatisData = [] // 非常不满意

      data.sort((prev, next) => prev.satisfication - next.satisfication).forEach(item => {
        yAxisData.push(item.displayName);
        verySatisData.push({
          value: item.verySatifaction,
          _origin: item
        });
        satisData.push({
          value: item.satisfication,
          _origin: item
        });
        generaldData.push({
          value: item.general,
          _origin: item
        });
        unsatisData.push({
          value: item.unSatisfication,
          _origin: item
        });
        veryUnSatisData.push({
          value: item.veryUnSatifaction,
          _origin: item
        });
      });
      series.push({
        name: USER_DEGREE_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: verySatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: satisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: generaldData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[3],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: unsatisData,
        itemStyle : { normal: {label : {show: true}}}
      })
      series.push({
        name: USER_DEGREE_LEGEND[4],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: veryUnSatisData,
        itemStyle : { normal: {label : {show: true}}}
      })
      
      return {
        title: t('report.statistics.title8'),
        legend: USER_DEGREE_LEGEND,
        color: USER_DEGREE_COLOR,
        yAxisData,
        series
      };
    },
    sortDegreeTable () {
      let series = [];
      let data = this.categoryData.degree || [];
      if(data.length == 0) return null;

      let yAxisData = [];
      let verySatisData = [] // 非常满意
      let satisData = [];// 满意
      let generaldData = [];// 一般
      let unsatisData = []; // 不满意
      let veryUnSatisData = [] // 非常不满意

      if(this.sort == t('common.base.satisfactionDegree.0')) {
        data.sort((prev, next) => prev.verySatifaction - next.verySatifaction);
      } else if(this.sort == t('common.base.satisfactionDegree.1')) {
        data.sort((prev, next) => prev.satisfication - next.satisfication);
      } else if(this.sort == t('common.base.satisfactionDegree.2')) {
        data.sort((prev, next) => prev.general - next.general);
      } else if(this.sort == t('common.base.satisfactionDegree.3')){
        data.sort((prev, next) => prev.unSatisfication - next.unSatisfication);
      }else{
        data.sort((prev, next) => prev.veryUnSatifaction - next.veryUnSatifaction);
      }

      data.forEach(item => {
        yAxisData.push(item.displayName);
        verySatisData.push({
          value: item.verySatifaction,
          _origin: item
        });
        satisData.push({
          value: item.satisfication,
          _origin: item
        });
        generaldData.push({
          value: item.general,
          _origin: item
        });
        unsatisData.push({
          value: item.unSatisfication,
          _origin: item
        });
        veryUnSatisData.push({
          value: item.veryUnSatifaction,
          _origin: item
        });
      });

      series.push({
        name: USER_DEGREE_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: verySatisData,
        itemStyle : { normal: {label : {show: true}}}
      })
      series.push({
        name: USER_DEGREE_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: satisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: generaldData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[3],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: unsatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[4],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: veryUnSatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        yAxisData,
        series
      };
    },
    getCategoryOption(option){
      let yAxisData = option.yAxisData;
      let that = this
      let start = 0;
      let end = yAxisData.length - 1;
      if(yAxisData.length > 10) start = end - 9;
      let originColor = []
      let originObj = {}
      if(this.categoryType == t('common.base.task')) {
        originObj = USER_TASK_OBJ
        originColor = USER_TASK_COLOR
      }else if(this.categoryType == t('report.eventScoreChart.label3')) {
        originObj = USER_EXPENSE_OBJ
        originColor = USER_EXPENSE_COLOR
      }else if(this.categoryType == t('common.base.degree')){
        originObj = USER_DEGREE_OBJ
        originColor = USER_DEGREE_COLOR
      }
      let _option = {
        color: option.color,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => {
            let staffId = params[0].data._origin.staffId
            let executorName = params[0].name
            let id = Math.ceil(Math.random() * 1000)

            let element = `<div id="echart-item_${id}"></div>`
            that.$nextTick(()=>{
              createVue({
                el:`#echart-item_${id}`,
                components: {
                  // [OpenDataComponent.name]: OpenDataComponent
                  'test-component': {
                    render(h) {
                      return h(
                        'div', null, [
                          isOpenData ? h('open-data', {
                            props:{
                              type:'userName',
                              openid:staffId
                            }
                          }) : null,
                          !isOpenData ? h('div', null, executorName) : null,
                          option.legend.length > 0 ?  option.legend.map((item, index) => {
                            return h('div', null, [
                                h('span', 
                                {
                                  style: {
                                    display: 'inline-block',
                                    width: '12px',
                                    height: '12px',
                                    backgroundColor: originColor[index],
                                    borderRadius: '50%',
                                    marginRight:'5px'
                                  }
                                }
                              ),
                                h('span', {style:'font-size:14px;'}, `${item}: ${params[0].data._origin[originObj[item]] || 0}`)
                              ]
                            )
                            
                          }) : null
                        ]
                      )
                    }
                  }
                },
                render(h) {
                  return (
                    <test-component />
                  )
                }
              })
              
            })
            return element;
          }
        },
        legend: {
          data: option.legend,
          top: '10px',
          left: '70px'
        },
        grid: {
          left: '20px',
          right: '60px',
          bottom: '20px',
          top: '50px',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {
              name: option.title
            }
          },
          right: 40
        },
        dataZoom: [
          {
            type: 'slider',
            show: true,
            yAxisIndex: [0],
            right: '20px',
            startValue: start,
            endValue: end,
            minValueSpan: 10,
            maxValueSpan: 30
          }
        ],
        yAxis: {
          type: 'category',
          data: option.yAxisData,
          axisLabel: {
            formatter(originText) {
              if (!originText) return '';
              if(originText.length <= 7 || that.isOpenData) {
                return originText
              }
              return `${originText.slice(0, 7)}...`;
            }
          },
        },
        xAxis: {
          type: 'value'
        },
        series: option.series
      };

      if(this.categoryType == t('report.staffCategoryChart.title9') && option.tooltip) {
        _.assign(_option.tooltip, option.tooltip);
      }

      if(option.xAxis) _.assign(_option.xAxis, option.xAxis)

      return _option;
    },
    formatterTime(sec){
      let date = sec;
      if(this.timeType === 'day'){
        date += t('common.base.day');
      }else if(this.timeType === 'hour'){
        date += t('common.base.hour1');
      }else if(this.timeType === 'minute'){
        date += t('common.base.minute');
      }
      return sec ? date : '--';
    },
    // 计算最大时间间隔
    computeInterval(sec){
      let interval = {
        min: 0,
        max: null
      }
      
      // 如果时间跨度不大于1小时
      if(sec <= 3600){
        // 以分钟为最小刻度
        interval.min = 60 ;
        // 以10分钟为最大刻度
        interval.max = 60 * 10;
        return interval;
      }

      // 如果时间跨度小于1天
      if(sec <= 3600 * 24){
        // 以小时为最小刻度
        interval.min = 3600;
        return interval;
      }

      // 如果时间跨度大于1天，则按6份划分
      let hour = sec / 3600 >> 0;
      interval.max = (hour / 6 >> 0) * 3600;
      interval.min = 3600;
      return interval
    },
    datePicker(data) {
      // 初始化时间
      let locTag = localStorage.getItem('tag')
      let timeType = localStorage.getItem('timeType')
      if (locTag) {
        this.tag = JSON.parse(locTag);
        this.categoryTeamId = this.tag.map(item => {return item.id}).join(',');
      }
      if(timeType) {
        this.timeType = timeType
      }
      localStorage.setItem('staffEfficiency', JSON.stringify([safeNewDate(data[0]), safeNewDate(data[1])]))
      this.initDate(data[0], data[1]);

      this.state && this.$track.commonFn.chartTrack(this.state, 'REPORT_SEARCH_TIME', this.$track)
    }
  },
  mounted(){
    this.initCategory();
    window.addEventListener('resize', _.debounce(function(){
      category.resize();
    }, 400))
    this.getTaskTypes()
  },
  watch: {
    categoryType(){
      this.showTable = false;
    },
    state: {
      immediate: true,
      handler(newValue, _) {
        if (newValue) {
          if (newValue === 'personnel-effectiveness') {
            this.chooseCategoryType(t('report.staffCategoryChart.title9'), t('common.base.task'))
          } else if (newValue === 'personnel-workload') {
            if(this.type === t('common.base.customer')) return this.chooseCategoryType(t('common.base.customer'), t('common.base.task'),t('common.base.customer'));

            this.chooseCategoryType(t('common.base.task'), t('common.base.task'))
          } else {
            this.chooseCategoryType(t('common.base.degree'), t('common.base.task'))
          }
        }
      }
    }
  },
  components: {
    [BaseCheckbox.name]: BaseCheckbox,
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>

<style lang="scss">
#category{
  height: 100%;
}
#customer {
  height: 100%;
}
.category-chart-wrap{
  width: 100%;
  height: 520px;
  position: relative;
}

.category-chart-empty{
  position: absolute;
  width: 100px;
  text-align: center;
  top: 120px;
  left: 50%;
  margin-left: -50px;
  font-size: 18px;
  font-weight: 500;
  color: #9a9a9a;
}
.stats-staff-category-wrap{
  //padding: 10px;
}
.el-tooltip__popper{
  max-width: 800px;
  word-break: break-all;
}
.task-flex {
    position: absolute;
    right: 20px;
    > span {
        display: inline-block;
        text-align: left;
        width: 80px;
    }
}
</style>

<style lang="scss" scoped>
.el-radio-button--small {
  ::v-deep .el-radio-button__inner {
    padding: 8px 15px;
  }
}
.stats-form-effectiveness {
  margin-top: 2px;
}
.stats-form > h3 {
  min-width: 120px;
}
</style>